<-- back

Longest Common Prefix

Link

First found the smallest string, just to avoid the IndexOutOfBound Exception and then just iterated through every string to make sure all their characters matched.

Full Solution in Java:

public class Solution { public String longestCommonPrefix(String[] strs) { if(strs.length==0){ return ""; } StringBuilder sb = new StringBuilder(); int min = Integer.MAX_VALUE; for(int i=0;i< strs.length; i++){ min = Math.min(strs[i].length(), min); } for(int j=0; j< min; j++){ char c = strs[0].charAt(j); for(int i=1; i< strs.length; i++){ if(strs[i].charAt(j)!=c){ return sb.toString(); } } sb.append(c); } return sb.toString(); } }